//
//  VRAddRiskReportViewController.m
//  VRFirefighting
//
//  Created by Veer on 2018/8/18.
//  Copyright © 2018年 Veer. All rights reserved.
//

#import "VRAddRiskReportViewController.h"

#import "VRAddRiskReportInputView.h"

#import "HXPhotoView.h"


@interface VRAddRiskReportViewController () <HXPhotoViewDelegate>

@property (nonatomic, strong) UIScrollView *contentScrollView1;
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) VRAddRiskReportInputView *inputView0;
@property (nonatomic, strong) VRAddRiskReportInputView *inputView1;
@property (nonatomic, strong) HXPhotoView *photoView;

@property (nonatomic, strong) HXPhotoManager *manager;

@end

@implementation VRAddRiskReportViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = ScrollViewBgColor;
    self.title = @"隐患报告";
    
    [self setupSubView];
}


- (void)setupSubView
{
    UIView *contentView = [[UIView alloc] init];
    [self.contentScrollView1 addSubview:contentView];
    self.contentView = contentView;
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.contentScrollView1);
        make.width.mas_equalTo(self.contentScrollView1);
    }];
    
    VRAddRiskReportInputView *inputView0 = [[VRAddRiskReportInputView alloc] init];
    inputView0.iconImage = [UIImage imageNamed:@"my_report_address"];
    inputView0.title = @"隐患地点";
    inputView0.placeholder = @"请输入隐患地址";
    [contentView addSubview:inputView0];
    self.inputView0 = inputView0;
    [inputView0 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(114);
    }];
    
    UIView *lineView0 = [[UIView alloc] init];
    lineView0.backgroundColor = ScrollViewBgColor;
    [contentView addSubview:lineView0];
    [lineView0 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(inputView0.mas_bottom);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(10);
    }];
    
    VRAddRiskReportInputView *inputView1 = [[VRAddRiskReportInputView alloc] init];
    inputView1.iconImage = [UIImage imageNamed:@"my_report_describe"];
    inputView1.title = @"隐患描述";
    inputView1.placeholder = @"请尽可能的描述隐患内容方便我们进行排查";
    [contentView addSubview:inputView1];
    self.inputView1 = inputView1;
    [inputView1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(inputView0.mas_bottom).offset(10);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(178);
    }];
    
    UIView *lineView1 = [[UIView alloc] init];
    lineView1.backgroundColor = ScrollViewBgColor;
    [contentView addSubview:lineView1];
    [lineView1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(inputView1.mas_bottom);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(10);
    }];
    
    
    UIView *bgView = [[UIView alloc] init];
    bgView.backgroundColor = [UIColor whiteColor];
    bgView.frame = CGRectMake(0, NAVIGATION_BAR_HEIGHT, kScreenWidth, 150);
    [contentView addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(inputView1.mas_bottom).offset(10);
        make.left.right.mas_equalTo(0);
//        make.height.mas_equalTo(180);
    }];
    
    UIImageView *iconImgView = [[UIImageView alloc] init];
    iconImgView.image = [UIImage imageNamed:@"my_report_up"];
    iconImgView.contentMode = UIViewContentModeScaleAspectFit;
    [bgView addSubview:iconImgView];
    [iconImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.top.mas_equalTo(14);
        make.width.mas_equalTo(16);
        make.height.mas_equalTo(16);
    }];
    
    UILabel *titleLbl = [[UILabel alloc] init];
    titleLbl.numberOfLines = 0;
    titleLbl.textColor = MAINColor;
    titleLbl.font = VRFont(16);
    titleLbl.text = @"上传图片";
    [bgView addSubview:titleLbl];
    [titleLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(iconImgView.mas_right).offset(4);
        make.centerY.mas_equalTo(iconImgView);
    }];
    
    HXPhotoView *photoView = [[HXPhotoView alloc] initWithFrame:CGRectMake(20, 40, kScreenWidth - 40, 400) manager:self.manager];
    photoView.lineCount = 5;
//    HXPhotoView *photoView = [[HXPhotoView alloc] init];
    photoView.backgroundColor = [UIColor whiteColor];
    photoView.delegate = self;
    photoView.backgroundColor = [UIColor whiteColor];
    [bgView addSubview:photoView];
    self.photoView = photoView;
//    [photoView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.mas_equalTo(10);
//        make.top.mas_equalTo(inputView1.mas_bottom).offset(10);
//        make.right.mas_equalTo(-10);
//        make.height.mas_equalTo(100);
//    }];
    [bgView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(photoView);
    }];
    
    
    UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    saveBtn.backgroundColor = RGB(78, 173, 57);
    saveBtn.layer.cornerRadius = 4;
    [saveBtn setTitle:@"提交" forState:UIControlStateNormal];
    saveBtn.titleLabel.font = VRFont(16);
    [saveBtn setTitleColor:RGB(255, 255, 255) forState:UIControlStateNormal];
    [saveBtn setTitleColor:RGB(120, 120, 120) forState:UIControlStateHighlighted];
    [saveBtn addTarget:self action:@selector(onSaveBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [contentView addSubview:saveBtn];
    [saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(contentView);
        make.top.mas_equalTo(bgView.mas_bottom).offset(60);
        make.width.mas_equalTo(290);
        make.height.mas_equalTo(40);
    }];
    
    [self.contentView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(saveBtn);
    }];
}


#pragma mark - networking
- (void)saveTestInfo
{

    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"UserID"] = [VRUser shareUser].token;
    param[@"address"] = self.inputView0.text;
    param[@"content"] = self.inputView1.text;
    
    weakify(self)
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = @"正在上传...";
    [JKNetworking uploadImageWith:AddRiskRepot parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        strongify(self)
        for (int i = 0; i < self.photoView.imageList.count; i++) {
            
            UIImage *image = self.photoView.imageList[i];
            NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
            // 在网络开发中，上传文件时，是文件不允许被覆盖，文件重名
            // 要解决此问题，
            // 可以在上传时使用当前的系统事件作为文件名
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            // 设置时间格式
            [formatter setDateFormat:@"yyyyMMddHHmmss"];
            NSString *dateString = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString  stringWithFormat:@"%@%d.jpg", dateString,i];
            /*
             *该方法的参数
             1. appendPartWithFileData：要上传的照片[二进制流]
             2. name：对应网站上[upload.php中]处理文件的字段（比如upload）
             3. fileName：要保存在服务器上的文件名
             4. mimeType：上传的文件的类型
             */
            [formData appendPartWithFileData:imageData name:@"files" fileName:fileName mimeType:@"image/jpeg"];
            //
        }
    } success:^(NSDictionary *responseObject) {
        
        strongify(self)
        NSLog(@"responseObject:%@", responseObject);
        NSInteger code = [responseObject[@"state"] integerValue];
        NSString *msg = responseObject[@"message"];
        if (code == 0) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [hud hideAnimated:YES];
                [SVProgressHUD showSuccessWithStatus:@"保存成功"];
            });
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self.navigationController popViewControllerAnimated:YES];
            });
            
        }else if(msg.length > 0){
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showErrorWithStatus:msg];
                [hud hideAnimated:YES];
            });
        }
    } error:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:@"未知错误"];
            [hud hideAnimated:YES];
        });
    }];
}




#pragma mark - action
- (void)onSaveBtnClick:(UIButton *)sender
{
    if (self.inputView0.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入隐藏地点"];
        return;
    }
    if (self.inputView1.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入隐藏描述"];
        return;
    }
    if (self.photoView.imageList == 0) {
        [SVProgressHUD showErrorWithStatus:@"请上传图片"];
        return;
    }
    [self saveTestInfo];
}


#pragma mark - HXPhotoViewDelegate
// 代理返回 选择、移动顺序、删除之后的图片以及视频
//- (void)photoView:(HXPhotoView *)photoView changeComplete:(NSArray<HXPhotoModel *> *)allList photos:(NSArray<HXPhotoModel *> *)photos videos:(NSArray<HXPhotoModel *> *)videos original:(BOOL)isOriginal
//{
//
//}

// 当view更新高度时调用
- (void)photoView:(HXPhotoView *)photoView updateFrame:(CGRect)frame
{
    
}

// 删除网络图片的地址
- (void)photoView:(HXPhotoView *)photoView deleteNetworkPhoto:(NSString *)networkPhotoUrl
{
    
}


- (void)photoView:(HXPhotoView *)photoView imageChangeComplete:(NSArray<UIImage *> *)imageList
{
    NSSLog(@"%@",imageList);
}



#pragma mark - lazy
- (UIScrollView *)contentScrollView1
{
    if (_contentScrollView1 == nil) {
        
        _contentScrollView1 = [[UIScrollView alloc] initWithFrame:self.view.bounds];
        _contentScrollView1.backgroundColor = [UIColor whiteColor];
        //        _contentScrollView1.delegate = self;
        //        _contentScrollView.bounces = NO;
        _contentScrollView1.alwaysBounceVertical = YES;
        //        _contentScrollView.delegate = self;
        if (@available(iOS 11.0, *)) {
            //            _contentScrollView1.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        [self.view addSubview:_contentScrollView1];
    }
    return _contentScrollView1;
}


- (HXPhotoManager *)manager {
    if (!_manager) {
        _manager = [[HXPhotoManager alloc] initWithType:HXPhotoManagerSelectedTypePhoto];
        _manager.configuration.selectTogether = NO;
        _manager.configuration.requestImageAfterFinishingSelection = YES;
    }
    return _manager;
}

@end
